<template>
  <div>
    <my-breadcrumb :items="['商家大全', '商家管理']"/>
    <search :formItems="searchItems" @search="getList" ref="search"/>
    <div class="add">
      <el-button type="primary" @click="toAdd">新增商家</el-button>
      <el-button type="primary" :loading="loading" @click="toExport">导出商家</el-button>
      <div style="display: inline-block;" v-if="selections.length">
        <el-button type="primary" @click="toMorePass(1)">批量审核通过</el-button>
        <el-button  type="primary" @click="toMorePass(2)">批量驳回</el-button>
      </div>
    </div>
    <el-table :data="merchant" @sort-change="orderByTime" @select="selectChange" @select-all="selectChange">
      <el-table-column
        type="index"
        width="55">
      </el-table-column>
      <el-table-column
        type="selection"
        :selectable="selectable"
        width="55">
      </el-table-column>
      <el-table-column
        label="创建时间"
        width="110px"
        sortable="custom"
        prop="createtime">
      </el-table-column>
      <el-table-column
        label="商家名称"
        prop="name">
      </el-table-column>
      <el-table-column
        label="手机号"
        prop="phone">
      </el-table-column>
      <el-table-column
        label="运营人数"
        prop="scaleid">
        <template slot-scope="scope">
          {{ scope.row.scaleid === '1' ? '3人以下' : (scope.row.scaleid === '1' ? '3-10人' : '10人以上') }}
        </template>
      </el-table-column>
      <el-table-column
        label="推荐"
        prop="topnum">
        <template slot-scope="scope">
          {{ scope.row.topnum === '1' ? '推荐商家' : '' }}
        </template>
      </el-table-column>
      <el-table-column
        label="商家等级"
        prop="level">
      </el-table-column>
      <el-table-column
        label="是否禁用"
        prop="islogin">
        <template slot-scope="scope">
          {{ scope.row.islogin === '1' ? '未禁用' : '已禁用' }}
        </template>
      </el-table-column>
      <el-table-column
        label="禁言状态"
        prop="prohibit">
        <template slot-scope="scope">
          {{ scope.row.prohibit === '1' ? '禁言' : '未禁言' }}
        </template>
      </el-table-column>
      <el-table-column
        label="审核状态"
        prop="placardstatus">
        <template slot-scope="scope">
          {{ scope.row.placardstatus === '0' ? '审核中' : (scope.row.placardstatus === '1' ? '审核通过' : '驳回') }}
        </template>
      </el-table-column>
      <el-table-column
        label="开店日期"
        width="110px"
        sortable="custom"
        prop="strattime">
      </el-table-column>
      <el-table-column
        label="经营范围"
        width="200px"
        prop="managementid">
        <template slot-scope="scope">
          <el-tag v-for="(item, index) in scope.row.managementid" :key="index" v-if="item">{{ managementid[item - 1].name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="禁言开始时间"
        width="110px"
        prop="start">
      </el-table-column>
      <el-table-column
        label="禁言结束时间"
        width="110px"
        prop="end">
      </el-table-column>
      <el-table-column
        label="禁言原因"
        prop="prohibitcontent">
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        width="190px">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="toUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="text" @click="toDelete(scope.row.id)">删除</el-button>
          <div style="display: inline-block;" v-if="scope.row.placardstatus === '0'">
            <el-button type="text" @click="toPass([scope.row.id], 1)">审核通过</el-button>
            <el-button type="text" @click="toPass([scope.row.id], 2)">驳回</el-button>
          </div>
          <el-dropdown @command="slotFn" v-else>
            <el-button size="mini" type="text">更多</el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-if="scope.row.islogin === '1'" :command="'disable-' + scope.row.memberid">禁用</el-dropdown-item>
              <el-dropdown-item v-else :command="'disable-' + scope.row.memberid + '-0'">启用</el-dropdown-item>
              <el-dropdown-item :command="'banned-' + scope.row.memberid" v-if="scope.row.prohibit === '0'">禁言</el-dropdown-item>
              <el-dropdown-item :command="'unbanned-' + scope.row.prohibitid" v-else>解除禁言</el-dropdown-item>
              <el-dropdown-item :command="`recommend-${scope.row.memberid}-${scope.row.topnum}`">{{ scope.row.topnum === '1' ? '取消推荐' : '设为推荐' }}</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNum"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total">
      </el-pagination>
    </div>
    <el-dialog :title="isAdd ? '新增商家' : '修改商家'" :visible.sync="showAdd" :close-on-click-modal="false" width="700px">
      <el-form :model="memberinfo" :rules="infoRules" inline label-width="90px" ref="addForm">
        <el-form-item label="头像" prop="avatar" style="width: 500px;">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload">
            <img v-if="memberinfo.avatar" :src="memberinfo.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="商家名称" prop="name">
          <el-input v-model="memberinfo.name"/>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input v-model="memberinfo.phone"/>
        </el-form-item>
        <el-form-item label="签名" prop="autograph">
          <el-input v-model="memberinfo.autograph"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="memberinfo.password" type="password"/>
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-input-number v-model="memberinfo.level" :min="0" :max="5"/>
        </el-form-item>
      </el-form>
      <el-form :model="detail" :rules="detailRules" inline label-width="90px" ref="detailForm">
        <el-form-item label="营业执照" prop="img" style="width: 500px;">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :before-upload="beforeUpload2">
            <img v-if="detail.license" :src="detail.license" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="运营人数" prop="scaleid">
          <el-select v-model="detail.scaleid">
            <el-option value="1" label="3人以下"/>
            <el-option value="2" label="4-10人"/>
            <el-option value="3" label="10人以上"/>
          </el-select>
        </el-form-item>
        <el-form-item label="开店时间" prop="strattime">
          <el-date-picker
            v-model="detail.strattime"
            value-format="yyyy-MM-dd"
            type="date"
            placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="经营范围" prop="managementid">
          <el-select multiple v-model="detail.managementid">
            <el-option v-for="(item, index) in managementid" :key="index" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="淘宝链接" prop="tblink">
          <el-input v-model="detail.tblink" style="width: 500px;"/>
        </el-form-item>
        <el-form-item label="微博链接" prop="wblink">
          <el-input v-model="detail.wblink" style="width: 500px;"/>
        </el-form-item>
        <!--<el-form-item label="审核状态" prop="placardstatus">-->
          <!--<el-select v-model="detail.placardstatus">-->
            <!--<el-option value="0" label="审核中"/>-->
            <!--<el-option value="1" label="通过"/>-->
            <!--<el-option value="2" label="不通过"/>-->
          <!--</el-select>-->
        <!--</el-form-item>-->
        <el-form-item label="不通过原因" prop="remarks" label-width="100px" v-if="detail.placardstatus === '2'">
          <el-input v-model="detail.remarks" type="textarea" style="width: 400px;"/>
        </el-form-item>
      </el-form>
      <div class="footer" slot="footer">
        <el-button type="primary" @click="toSubmit">提交</el-button>
        <el-button type="danger" @click="showAdd = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="禁言用户" :visible.sync="showBanned" width="500px">
      <el-form :model="banned" ref="banned" label-width="70px">
        <el-form-item label="禁言时间" prop="times">
          <el-date-picker
            v-model="banned.times"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="禁言原因" prop="content">
          <el-input v-model="banned.content" type="textarea"/>
        </el-form-item>
      </el-form>
      <div class="footer" slot="footer">
        <el-button type="primary" @click="toSubmitBanned">提交</el-button>
        <el-button type="danger" @click="showBanned = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CLAZZ from '@/config/classify'
import {toExport, deleteRow} from '../../utils/getList'
export default {
  name: 'merchant',
  data () {
    return {
      searchItems: [
        {
          label: '商家名称',
          type: 'input',
          key: 'name'
        },
        {
          label: '手机号码',
          type: 'input',
          key: 'phone'
        },
        {
          label: '等级',
          type: 'input',
          key: 'level'
        },
        {
          label: '运营人数',
          type: 'select',
          key: 'scaleid',
          options: [{id: '1', name: '3人以下'}, {id: '2', name: '4-10人'}, {id: '3', name: '10人以上'}]
        },
        {
          label: '经营范围',
          type: 'selects',
          key: 'managementid',
          options: CLAZZ.managementid
        },
        {
          label: '开店日期',
          type: 'times',
          key: 'times'
        },
        {
          label: '注册日期',
          type: 'times',
          key: 'times2'
        },
        {
          label: '是否推荐',
          key: 'topnum',
          type: 'select',
          options: [{id: '1', name: '是'}, {id: '0', name: '否'}]
        },
        {
          label: '审核状态',
          type: 'select',
          key: 'placardstatus',
          options: [{id: '0', name: '审核中'}, {id: '1', name: '审核通过'}, {id: '2', name: '驳回'}]
        },
        {
          label: '是否禁用',
          key: 'islogin',
          type: 'select',
          options: [{id: '1', name: '是'}, {id: '0', name: '否'}]
        },
        {
          label: '是否禁言',
          key: 'prohibit',
          type: 'select',
          options: [{id: '1', name: '是'}, {id: '0', name: '否'}]
        }
      ], // 检索结构
      merchant: [],
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0
      },
      loading: false,
      lifting: null,
      managementid: CLAZZ.managementid,
      levels: CLAZZ.level,
      isAdd: true,
      showAdd: false,
      updateRow: null,
      memberinfo: {
        name: '',
        phone: '',
        password: '',
        autograph: '',
        // level: '',
        // fabulous: 0,
        // fans: 0,
        islogin: '1',
        // number: '',
        avatar: '',
        level: 0
      },
      infoRules: {
        name: [
          { required: true, message: '请输入商家名称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { type: 'string', pattern: /^[1]([3-9])[0-9]{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        // password: [
        //   { required: true, message: '请输入密码', trigger: 'blur' }
        // ],
        level: [
          { required: true, message: '请输入等级', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '请选择用户头像', trigger: 'change' }
        ]
      },
      detail: {
        scaleid: '',
        strattime: '',
        managementid: [],
        tblink: '',
        wblink: '',
        license: '',
        placardstatus: '1', // 0不能 1能
        remarks: ''
      },
      detailRules: {
        scaleid: [
          { required: true, message: '请输入运营人数', trigger: 'blur' }
        ],
        strattime: [
          { required: true, message: '请输入开店时间', trigger: 'blur' }
        ],
        managementid: [
          { required: true, message: '请选择经营范围', trigger: 'blur' }
        ]
      },
      banned: {
        times: [],
        content: ''
      },
      showBanned: false,
      bannedId: '',
      selections: [],
      placardstatus: ''
    }
  },
  methods: {
    getList () {
      let searchData = {}
      if (this.$refs['search']) {
        searchData = this.$refs['search'].search()
      }
      let params = {...searchData, page: this.page.pageNum, size: this.page.pageSize, orderby: this.lifting}
      this.axios.get('/Business/index', {params})
        .then(res => {
          if (res.data.status) {
            this.page.total = Number(res.data.data.count)
            res.data.data.list.forEach(item => {
              item.managementid = item.managementid ? item.managementid.split(',') : item.managementid
            })
            this.merchant = res.data.data.list
          }
        })
    },
    handleSizeChange (e) {
      this.page.pageSize = e
      this.getList()
    },
    handleCurrentChange (e) {
      this.page.pageNum = e
      this.getList()
    },

    beforeUpload (file) {
      let reader = new FileReader()
      let _self = this
      reader.onload = function (ev) {
        _self.memberinfo.avatar = ev.currentTarget.result
      }
      reader.readAsDataURL(file)
      return false
    },
    beforeUpload2 (file) {
      let reader = new FileReader()
      let _self = this
      reader.onload = function (ev) {
        _self.detail.license = ev.currentTarget.result
      }
      reader.readAsDataURL(file)
      return false
    },

    toAdd () {
      this.isAdd = true
      this.showAdd = true
      this.$nextTick(() => {
        this.$refs['addForm'].resetFields()
        this.$refs['detailForm'].resetFields()
        this.$refs['addForm'].clearValidate()
        this.$refs['detailForm'].clearValidate()
      })
    },
    toUpdate (row) {
      this.isAdd = false
      this.updateRow = row
      this.showAdd = true
      this.$nextTick(() => {
        Object.keys(row).forEach(key => {
          if (this.memberinfo[key] !== undefined) {
            this.memberinfo[key] = row[key]
          }
          if (key === 'password') {
            this.memberinfo.password = ''
          }
          if (this.detail[key] !== undefined) {
            this.detail[key] = row[key]
          }
        })
        this.$refs['addForm'].clearValidate()
        this.$refs['detailForm'].clearValidate()
      })
    },
    toSubmitNext () {
      let params = {
        memberinfo: {},
        detail: {}
      }
      let url = '/business/add'
      Object.keys(this.memberinfo).forEach(key => {
        params.memberinfo[key] = this.memberinfo[key]
      })
      Object.keys(this.detail).forEach(key => {
        params.detail[key] = this.detail[key]
        if (this.detail[key] instanceof Array) {
          params.detail[key] = this.detail[key].join(',')
        }
      })
      if (!this.isAdd) {
        params.id = this.updateRow.id
        url = '/business/edit'
      }
      this.axios.post(url, this.qs.stringify(params))
        .then(res => {
          if (res.data.status === 1) {
            this.$message.success(res.data.msg)
            this.showAdd = false
            this.getList()
          }
        })
    },
    toSubmit () {
      let count = 0
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          count++
        } else {
          this.$message.error('请检查表单是否填写正确')
          return false
        }
      })
      this.$refs['detailForm'].validate((valid) => {
        if (valid) {
          count++
        } else {
          this.$message.error('请检查表单是否填写正确')
          return false
        }
      })
      if (count === 2) {
        this.toSubmitNext()
      }
    },
    toDelete (id) {
      deleteRow({url: '/business/delete', id}, res => {
        if (res.data.status === '1' || res.data.status === 1) {
          this.$message.success(res.data.msg)
          this.getList()
        }
      })
    },

    slotFn (command) {
      let arr = command.split('-')
      if (arr[0] === 'disable') {
        this.toDisable(arr[1], arr[2])
      } else if (arr[0] === 'banned') {
        this.toBanned(arr[1])
      } else if (arr[0] === 'recommend') {
        this.toRecommend(arr[1], arr[2])
      } else if (arr[0] === 'unbanned') {
        this.toUnbanned(arr[1])
      }
    },
    toUnbanned (id) {
      this.$confirm('确认解除禁言吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/Member/delprohibit', {params: {prohibitid: id}})
          .then(res => {
            if (res.data.status === '1' || res.data.status === 1) {
              this.$message.success(res.data.msg)
              this.getList()
            }
          })
      })
    },
    toDisable (id, flag) {
      let message = '此操作将禁用该用户, 是否继续?'
      if (flag) {
        message = '此操作将启用该用户, 是否继续?'
      }
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/Member/nologin', {params: {memberid: id}})
          .then(res => {
            if (res.data.status === 1) {
              this.$message.success(res.data.msg)
            }
            this.getList()
          })
      })
    },
    toBanned (id) {
      this.bannedId = id
      this.showBanned = true
      this.$nextTick(() => {
        this.$refs['banned'].resetFields()
      })
    },
    toSubmitBanned () {
      let params = {
        memberid: this.bannedId,
        start: this.banned.times[0],
        end: this.banned.times[1],
        content: this.banned.content
      }
      this.axios.post('/Member/prohibit', this.qs.stringify(params))
        .then(res => {
          if (res.data.status === 1) {
            this.showBanned = false
            this.$message.success(res.data.msg)
            this.getList()
          }
        })
    },
    toRecommend (id, type) {
      let params = {
        id,
        topnum: ''
      }
      type === '1' ? params.topnum = '0' : params.topnum = '1'
      let msg = '确定设置该商家为推荐商家吗？'
      if (type === '1') {
        msg = '确定把推荐商家移除吗？'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.get('/Business/istopnum', {params})
          .then(res => {
            if (res.data.status === 1) {
              this.$message.success(res.data.msg)
              this.getList()
            }
          })
      })
    },

    toExport () {
      this.loading = true
      let searchData = this.$refs['search'].search()
      toExport('/Business/excelindex', searchData, '商家', () => {
        this.loading = false
      })
    },

    orderByTime (lifting) {
      if (lifting.order === 'ascending') {
        this.lifting = lifting.prop + ' asc'
      } else {
        this.lifting = lifting.prop + ' desc'
      }
      this.getList()
    },

    selectChange (selection) {
      this.selections = selection
    },
    toMorePass (type) {
      let temp = []
      this.selections.forEach(item => {
        temp.push(item.id)
      })
      this.toPass(temp, type)
    },

    toPass (id, type) {
      if (type === 1) {
        this.$confirm('确认审核通过吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.toReview({id, placardstatus: type})
        })
      } else if (type === 2) {
        this.$prompt('请输入驳回原因', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[\s\S]*.*[^\s][\s\S]*$/,
          inputErrorMessage: '请输入原因'
        }).then(({ value }) => {
          this.toReview({id, placardstatus: type, remarks: value})
        })
      }
    },
    toReview (params) {
      this.axios.post('/Business/examine', this.qs.stringify(params))
        .then(res => {
          if (res.data.status === 1) {
            this.$message.success(res.data.msg)
            this.getList()
          }
        })
    },

    selectable (row, index) {
      return (row.delflag === '0' && row.placardstatus === '0')
    }
  },
  created () {
    this.getList()
  }
}
</script>

<style scoped>
  .avatar-uploader-icon:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
